import numpy as np
import cv2
import base64

from __future__ import print_function
import numpy
import PIL.Image
import pickle
import matplotlib.pyplot
import pdb


def getByte(path):
    with open(path, 'rb') as f:
        img_byte = base64.b64encode(f.read())
    img_str = img_byte.decode('ascii')
    return img_str

img_str = getByte('../face_/sample/heyang.jpg')
# 此时可以测试解码得到图像并显示，服务器端也按照下面的方法还原图像继续进一步处理
img_decode_ = img_str.encode('ascii')  # ascii编码
img_decode = base64.b64decode(img_decode_)  # base64解码
img_np = np.frombuffer(img_decode, np.uint8)  # 从byte数据读取为np.array形式
img = cv2.imdecode(img_np, cv2.COLOR_RGB2BGR)  # 转为OpenCV形式

# 显示图像
cv2.imshow('img', img)
cv2.waitKey()
cv2.destroyAllWindows()

class Operation(object):
    image_base_path = "../image/"
    data_base_path = "../data/"

    def array_to_image(self, filename):
        '''
        从二进制文件中读取数据并重新恢复为图片
        '''
        with open(self.data_base_path + filename, mode='rb') as f:
            arr = pickle.load(f)  # 加载并反序列化数据
        rows = arr.shape[0]  # rows=5
        # pdb.set_trace()
        # print("rows:",rows)
        arr = arr.reshape(rows, 3, 32, 32)
        print(arr)  # 打印数组
        for index in range(rows):
            a = arr[index]
            # 得到RGB通道
            r = PIL.Image.fromarray(a[0]).convert('L')
            g = PIL.Image.fromarray(a[1]).convert('L')
            b = PIL.Image.fromarray(a[2]).convert('L')
            image = PIL.Image.merge("RGB", (r, g, b))
            # 显示图片
            matplotlib.pyplot.imshow(image)
            matplotlib.pyplot.show()
        # image.save(self.image_base_path + "result" + str(index) + ".png",'png')


if __name__ == "__main__":
    my_operator = Operation()
    images = []
    for j in range(5):
        images.append(str(j) + ".png")
    #	my_operator.image_to_array(images)
    my_operator.array_to_image('data2.bin')



